package com.zzm.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzm.demo.pojo.LogEntity;
import com.zzm.demo.pojo.User;
import com.zzm.demo.service.IUserService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author zzm
 * @version V1.0
 * @Description:该类只是Demo类，并未严格分层，只是作为入门的curd
 * @date 2017/9/19 12:13
 */
@Controller
public class UserController {
    static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService iUserService;
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    //生成日志，会输出到logstash
    @RequestMapping("/log/{id}/{name}/{info}")
    @ResponseBody
    public Object log(@PathVariable String id, @PathVariable String name, @PathVariable String info) {
        LogEntity logEntity = new LogEntity();
        logEntity.setId(id);
        logEntity.setName(name);
        logEntity.setInfo(info);
        log.info(JSONObject.toJSONString(logEntity));
        return "true";
    }

    //保存文档实体
    @GetMapping("/user/insert/{id}/{name}/{age}")
    @ResponseBody
    public Object insert(@PathVariable String id, @PathVariable String name, @PathVariable Integer age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        IndexQuery indexQuery = new IndexQueryBuilder().withId(user.getId()).withObject(user).build();
        elasticsearchTemplate.index(indexQuery);
        return "success";
    }
    //更新文档实体
    @RequestMapping("/user/update/{id}/{name}/{age}")
    @ResponseBody
    public Object update(@PathVariable String id, @PathVariable String name, @PathVariable Integer age) {
        NativeSearchQueryBuilder searchBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("id", id)); //term 为绝对匹配
        searchBuilder.withQuery(queryBuilder);
        long num = elasticsearchTemplate.count(searchBuilder.build(), User.class);
        if (num < 1) {
            throw new RuntimeException("不存在id:" + id);
        }
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        //该操作为upsert操作，会更新id数据
        IndexQuery indexQuery = new IndexQueryBuilder().withId(user.getId()).withObject(user).build();
        elasticsearchTemplate.index(indexQuery);
        return "success";
    }

    @GetMapping("/user/select/{name}/{age}")
    @ResponseBody
    public Object select(@PathVariable String name, @PathVariable Integer age) {
        NativeSearchQueryBuilder searchBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.should(QueryBuilders.matchPhraseQuery("name", name))  //短语匹配
                .should(QueryBuilders.matchQuery("age", age));     //age会被分词匹配（如果被分词）
        searchBuilder.withQuery(queryBuilder)
                .withSort(new FieldSortBuilder("id").order(SortOrder.ASC))//id asc
                .withPageable(new PageRequest(0, 10));                   //分页
        List<User> users = elasticsearchTemplate.queryForList(searchBuilder.build(), User.class);
        for (User user : users) {
            log.info(user.toString());
        }
        return users;
    }

    @GetMapping("/user/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable String id) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.should(QueryBuilders.termQuery("id", id)); //term 为绝对匹配
        DeleteQuery deleteQuery = new DeleteQuery();
        deleteQuery.setQuery(queryBuilder);
        elasticsearchTemplate.delete(deleteQuery,User.class);
        return "success";
    }

}
